package com.studentsystem.realm;

import com.studentsystem.dataobject.UserDO;
import com.studentsystem.service.UserService;
import com.studentsystem.shiro.JwtToken;
import com.studentsystem.shiro.profile.UserProfile;
import com.studentsystem.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserService userService;
    
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     *  角色的权限信息集合，授权时使用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserProfile userProfile = null;
        String username = null;
        if (principals != null) {
            userProfile = (UserProfile) principals.getPrimaryPrincipal();
            username = userProfile.getUsername();
        }

        UserDO user = userService.queryByUsername(username);

        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }

        // Todo 缓存Value
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.addRole(user.getRole());
        return authorizationInfo;
    }

    /**
     *  用户的角色信息集合，认证时使用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String jwtToken = (String) token.getCredentials();

        String username = jwtUtils.getUsernameByToken(jwtToken);

        UserDO user = userService.queryByUsername(username);

        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }

        UserProfile userProfile = new UserProfile();

        BeanUtils.copyProperties(user, userProfile);

        return new SimpleAuthenticationInfo(userProfile, token.getPrincipal(), getName());
    }
}
